package com.machine.filling.function.main.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.machine.filling.MyApp;
import com.machine.filling.R;
import com.machine.filling.Test.TestCommon;
import com.machine.filling.Test.TestFgFragment;
import com.machine.filling.base.baseMvp.BaseActivity;
import com.machine.filling.db.dao.AdDao;
import com.machine.filling.db.dao.CardTempDao;
import com.machine.filling.db.dao.ClientInfoDao;
import com.machine.filling.db.dao.ExceptionOrderDao;
import com.machine.filling.db.dao.GunInfoDao;
import com.machine.filling.db.dao.TempOrderDao;
import com.machine.filling.db.modle.AdModle;
import com.machine.filling.db.modle.CardTempModle;
import com.machine.filling.function.init.INextFragment;
import com.machine.filling.function.main.PayRes.PayResFragment;
import com.machine.filling.function.main.activity.adapter.AdPagerAdapter;
import com.machine.filling.function.main.cardInfoFg.CardInfoFgFragment;
import com.machine.filling.function.main.cardWarningFg.CardWarningFgFragment;
import com.machine.filling.function.main.error.ErrorFragment;
import com.machine.filling.function.main.erweima.ErWeiMaFragment;
import com.machine.filling.function.main.fuelingFg.FuelingFgFragment;
import com.machine.filling.function.main.orderInfoFg.OrderInfoFgFragment;
import com.machine.filling.function.main.payChoose.PayChooseFragment;
import com.machine.filling.function.main.topFg.TopFgFragment;
import com.machine.filling.function.set.SetActivity;
import com.machine.filling.net.http.network.OkhttpUtils;
import com.machine.filling.net.http.response.ADListResBean;
import com.machine.filling.net.http.response.PayByCashResBean;
import com.machine.filling.net.serialPort.receive.Receive_EndFueling;
import com.machine.filling.net.serialPort.receive.Receive_MachineState;
import com.machine.filling.net.serialPort.receive.Receive_PrepareFueling;
import com.machine.filling.net.serialPort.send.CMD_OrderFueling;
import com.machine.filling.net.serialPort.send.CMD_OrderFuelingCancle;
import com.machine.filling.net.serialPort.util.SerialPortSendUtil;
import com.machine.filling.net.serialPort.util.SerialPortToolManager;
import com.machine.filling.net.ws.response.WsResCardInfoBean;
import com.machine.filling.net.ws.response.WsResPayByCard;
import com.machine.filling.net.ws.response.WsResTopGunsInfoBean;
import com.machine.filling.ui.view.NoPreloadViewPager;
import com.machine.filling.util.Common;
import com.machine.filling.util.CustomToast;
import com.machine.filling.util.HexUtils;
import com.machine.filling.util.SpUtils;
import com.machine.filling.util.computer.ArithUtil;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.LogRecord;

import okhttp3.Request;

/**
 * Created by Administrator on 2018/3/14 0014.
 */

public class MainFuelActivity extends BaseActivity<MainFuelContract.Presenter> implements MainFuelContract.View, View.OnClickListener {
    private LinearLayout ll;
    private LinearLayout llPoints;
    private FrameLayout frame_left;
    private FrameLayout frame_right;

    private AdPagerAdapter adPagerAdapter2;
    private List<ADListResBean.AdListBean> adList2;
    private List<AdModle> adModleList;//广告

    //空闲
    public void TestFree(View view) {
        TestCommon.TEST_SERIAL_DATA = TestCommon.TEST_SERIAL_DATA_FREE;
    }

    //加油前准备
    public void TestPrepare(View view) {
        TestCommon.TEST_SERIAL_DATA = TestCommon.TEST_SERIAL_DATA_8101;
    }

    //授权油卡
    public void TestAgree(View view) {
        TestCommon.TEST_SERIAL_DATA = TestCommon.TEST_SERIAL_DATA_AGREE;
    }

    //加油中
    public void TestFueling(View view) {
        TestCommon.TEST_SERIAL_DATA = TestCommon.TEST_SERIAL_DATA_FUELING;
    }

    //加油结束
    public void TestEnd(View view) {
        TestCommon.TEST_SERIAL_DATA = TestCommon.TEST_SERIAL_DATA_END;
    }

    //交易确认
    public void Deal(View view) {
        SerialPortToolManager.getInstance().sendSerialPortCMD_DATA(TestCommon.testSerialPort, SerialPortSendUtil.getInstance().getCmd_DealConfirm_1002("10", "01", "0033"));
    }

    //删除所有临时卡数据库
    public void DelTempCard(View view) {
//        CardTempDao.getInstance().deleteAll();
//        TempOrderDao.getInstance().deleteAll();
//        ClientInfoDao.getInstance().deleteAll();
//        ExceptionOrderDao.getInstance().deleteAll();
        AdDao.getInstance().deleteAll();
    }


    //修改油机价格 7efe 1001 1104 0f 06 81 00000000 20151121175213 16 01 af7c 0d  --
    //            7efe 1001 1104 10 01 01 00000000 00201804141135420000167f0d
    //            7efe 1001 1104 10 01 01 01000000 0020180414120946 00 00 1f2f 0d
    //            7efe 1001 1104 0e    82 00000000 20151121175213 16 01 c2b3 0d
    public void ChengeMachinePrice(View view) {
//        CMD_SetMachine cmd__setMachine = new CMD_SetMachine();
//        cmd__setMachine.setGunNum_1("02");
//        cmd__setMachine.setUnitPrice_1("0199");
//        cmd__setMachine.setMidu_4("00000000");
//        cmd__setMachine.setTime_7(DateUtils.getCurrentTimeYMDHMS2());
//        cmd__setMachine.setTypeName_1("00");
//        cmd__setMachine.setStationName_1("00");
//        SerialPortToolManager.getInstance().sendSerialPortCMD_DATA(TestCommon.testSerialPort,
//                SerialPortSendUtil.getInstance().getCmd_SetMachine_1104(
//                        "10", "01",
//                        cmd__setMachine.getHexStr())
//        );
    }

    //修改卡机
    public void ChengeKjPrice(View view) {
//        CMD_SetKaJi cmd__setKaJi = new CMD_SetKaJi();
//        cmd__setKaJi.setGunNum_2("3032");
//        cmd__setKaJi.setPrice_5("30352E3939");
//        cmd__setKaJi.setYouhui_4("302E3035");
//        cmd__setKaJi.setTime_14("3230303831313033313632393335");
//        cmd__setKaJi.setTypeName_8("2D323023C6FBD3CD");
//        cmd__setKaJi.setStationName_18("B8DFD0C2C7F8CEE0CDA9BDD6BCD3D3CDD5BE");
//        SerialPortToolManager.getInstance().sendSerialPortCMD_DATA(TestCommon.testSerialPort,
//                SerialPortSendUtil.getInstance().getCmd_SetKj_910A(
//                        "10", "01", cmd__setKaJi.getHexStr()));
    }

    //预约加油  定量加油
    public void OrderFueling(View view) {
        CMD_OrderFueling orderFueling = new CMD_OrderFueling();
        orderFueling.setOrderMoney_7(HexUtils.str2ASCII("123.50", 7));
        orderFueling.setYouhuiMoney_5(HexUtils.str2ASCII("1.23", 5));
//        orderFueling.setPingzhenghao_2(SpUtils.getInstance(mContext).getNextPingZhengHao());//00000458
        orderFueling.setPingzhenghao_2("003E");//00000458
        SerialPortToolManager.getInstance().sendSerialPortCMD_DATA(TestCommon.testSerialPort,
                SerialPortSendUtil.getInstance().getCmd_StartOrderFueling110A(
                        "10", "01", orderFueling.getHexStr()));
    }

    //取消预约加油
    public void CancleOrderFueling(View view) {
        CMD_OrderFuelingCancle cancle = new CMD_OrderFuelingCancle();
        cancle.setOrderMoney_7(HexUtils.str2ASCII("12", 7));
        cancle.setLiushuihao_2("0000");
        SerialPortToolManager.getInstance().sendSerialPortCMD_DATA(TestCommon.testSerialPort,
                SerialPortSendUtil.getInstance().getCmd_StartOrderFueling110B(
                        "10", "02", cancle.getHexStr()));
    }

    //锁枪
    public void LockGun(View view) {
        mPresenter.port_sendCMD_LockGun(TestCommon.testSerialPort, "10", "01");
    }

    //开枪
    public void UnLockGun(View view) {
        mPresenter.port_sendCMD_UnLockGun(TestCommon.testSerialPort, "10", "01");
    }

    //关闭
    public void Back(View view) {
        finish();
    }

    /**
     * 自助
     *
     * @param view
     */
    public void Self(View view) {
        mPresenter.port_sendCMD_Self(TestCommon.testSerialPort, "10", "01", true);
    }

    /**
     * 非自助
     *
     * @param view
     */
    public void UnSelf(View view) {
        mPresenter.port_sendCMD_Self(TestCommon.testSerialPort, "10", "01", false);
    }

    //--------------------以上为test------------------------------------------------------------------
    //轮播图循环播放
    //异常订单循环提交
    private static final int ERROR_HTTP_CYCLE = 1;

    private static final String TAG = "MainFuelActivity";
    private FragmentManager fm;
    private ImageView iv_set;
    private RecyclerView recyclerView;
    //这两个很重要 控制着是否数据更新到ui

    private Map<String, String> stateSerialNumMap;//串口号与 油机状态 的映射关系
    private Map<String, FuelingFgFragment> fuelFgSerialNumMap;//加油界面与串口的映射关系
    private Map<String, TopFgFragment> topFgSerialNumMap;//加油界面与串口的映射关系
    private Map<String, Boolean> portNumPreOrder;//串口与预约的关系
    private Map<String, String> portNumPreOrderNum;//串口与预约订单号的关系

    private Map<String, String> currentFragmentTag;//<串口号,fragmentTag>对应的当前界面的fragmentTag

    @Override
    public View initViews() {
        setContentView(R.layout.activity_fuel);
        mVp = (NoPreloadViewPager) findViewById(R.id.vp_top);
        ll = (LinearLayout) findViewById(R.id.ll);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 2));

        iv_set = (ImageView) findViewById(R.id.iv_set);
        llPoints = (LinearLayout) findViewById(R.id.llPoints);
        iv_set.setOnClickListener(this);
        frame_left = (FrameLayout) findViewById(R.id.frame_left);
        frame_right = (FrameLayout) findViewById(R.id.frame_right);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);//解决播放视频时的 黑屏问题
        return null;
    }


    @Override
    public void initDatas() {
        initCommunication();
        mPresenter.http_getAdListDay();
        // TODO: 2018/5/20 0020  提交异常的网络请求
//        handler.sendEmptyMessage(ERROR_HTTP_CYCLE);
        if (TestCommon.isTestSmall) {
            FragmentTransaction ft1 = fm.beginTransaction();
            FragmentTransaction ft2 = fm.beginTransaction();
            ft1.replace(R.id.frame_left, new TestFgFragment(R.layout.fg_fg_top)).commit();
            ft2.replace(R.id.frame_right, new TestFgFragment(R.layout.fg_fg_card)).commit();
        }
    }

    /**
     * 更换fragment
     *
     * @param fragment
     */
    private void replaceFragment(String portNum, Fragment fragment, @IdRes int framelayoutId, String fgTag) {
        FragmentTransaction ft = fm.beginTransaction();
        if (this.hasWindowFocus()) {
            ft.replace(framelayoutId, fragment, fgTag).commit();
        }
        //保存串口号对应的当前油机界面的fragmentTag值
        currentFragmentTag.put(portNum, fgTag);
    }

    /**
     * 显示首页  显示每个frame的同时
     *
     * @param portNum 串口号
     */
    private void showTop(final String portNum, boolean isUpdate) {
//        TopFgFragment topFgFragment = null;
//        if (isUpdate) {
//            topFgFragment = topFgSerialNumMap.get(portNum);
//            topFgFragment.updataeUi(mPresenter.getOilGunBeanByPortNum(portNum));
//        } else {
//            topFgFragment = new TopFgFragment();
//            topFgFragment.setDatas(mPresenter.getOilGunBeanByPortNum(portNum));
//            topFgFragment.setCardInListener(new TopFgFragment.CardInListener() {
//                @Override
//                public boolean isCardIn() {
//                    return Common.OIL_STATE_CARD_IN.equals(stateSerialNumMap.get(portNum));
//                }
//            });
//            topFgFragment.setINextFragment(new INextFragment() {
//                @Override
//                public void replaceNext(Intent intent, String className) {
//                    if (className.equals(CardWarningFgFragment.class.getName())) {
//                        showWaringCard(portNum);
//                    } else if (className.equals(CardInfoFgFragment.class.getName())) {
//
//                    } else if (className.equals(OrderInfoFgFragment.class.getName())) {
//                        showOrderInfoQuery(portNum);
//                    }
//                }
//            });
//            replaceFragment(portNumtopFgFragment, mPresenter.getFramLayoutIdBySerialNum(portNum), TopFgFragment.class.getName()+ portNum);
//            topFgSerialNumMap.put(portNum, topFgFragment);
//        }

        Fragment fragment = getSupportFragmentManager().findFragmentByTag(TopFgFragment.class.getName() + portNum);
        TopFgFragment topFgFragment = null;
        if (fragment == null) {
            /*if (isUpdate) {
                topFgFragment = topFgSerialNumMap.get(portNum);
                topFgFragment.updataeUi(mPresenter.getOilGunBeanByPortNum(portNum));
            } else {*/
            topFgFragment = new TopFgFragment();
            topFgFragment.setDatas(mPresenter.getOilGunBeanByPortNum(portNum));
            topFgFragment.setCardInListener(new TopFgFragment.CardInListener() {
                @Override
                public boolean isCardIn() {
                    return Common.OIL_STATE_CARD_IN.equals(stateSerialNumMap.get(portNum));
                }
            });
            topFgFragment.setINextFragment(new INextFragment() {
                @Override
                public void replaceNext(Intent intent, String className) {
                    if (className.equals(CardWarningFgFragment.class.getName())) {
                        showWaringCard(portNum);
                    } else if (className.equals(CardInfoFgFragment.class.getName())) {

                    } else if (className.equals(OrderInfoFgFragment.class.getName())) {
                        showOrderInfoQuery(portNum);
                    }
                }
            });
            replaceFragment(portNum, topFgFragment, mPresenter.getFramLayoutIdBySerialNum(portNum), TopFgFragment.class.getName() + portNum);
            topFgSerialNumMap.put(portNum, topFgFragment);
            /*}*/
        } else {
            if (fragment instanceof TopFgFragment) {
                topFgFragment = (TopFgFragment) fragment;
                topFgFragment.updataeUi(mPresenter.getOilGunBeanByPortNum(portNum));
            } else {
                Log.d(TAG, "showFueling() returned: " + "首页---的界面异常");
            }
        }
    }

    /**
     * 提示插卡
     *
     * @param portNum 串口号
     */

    private void showWaringCard(final String portNum) {
        CardWarningFgFragment cardWarningFgFragment = new CardWarningFgFragment();
        cardWarningFgFragment.setINextFragment(new INextFragment() {
            @Override
            public void replaceNext(Intent intent, String className) {
                if (className.equalsIgnoreCase(TopFgFragment.class.getName())) {
                    showTop(portNum, false);
                }
            }
        });
        replaceFragment(portNum, cardWarningFgFragment, mPresenter.getFramLayoutIdBySerialNum(portNum), CardWarningFgFragment.class.getName() + portNum);
    }

    /**
     * 显示油卡信息
     *
     * @param portNum 串口号
     */
    private void showCardInfo(final String portNum, final Receive_PrepareFueling cmd_prepare) {
        CardInfoFgFragment cardInfoFgFragment = new CardInfoFgFragment();

        cardInfoFgFragment.setCardInfo(portNum, mPresenter.getOilGunBeanByPortNum(portNum).getGunId() + "",
                cmd_prepare.getCardNum(), cmd_prepare.getCardCode(), cmd_prepare);

        cardInfoFgFragment.setINextFragment(new INextFragment() {
            @Override
            public void replaceNext(Intent intent, String className) {
                if (TopFgFragment.class.getName().equals(className)) {
                    showTop(portNum, false);
                }
            }
        });
        //界面获取到http卡信息后.立即向油机发送下发卡信息1101命令
        cardInfoFgFragment.setCardInfoReceiveListener(new CardInfoFgFragment.HttpCardInfoReceiveListener() {
            @Override
            public void httpCardInfoResult(WsResCardInfoBean cardInfoBean) {

                Log.d(TAG, "----->>: " + "获取到油卡信息");
                mPresenter.port_sendCardInfo_1101(portNum, cardInfoBean, cmd_prepare);
                CardTempDao.getInstance().deleteByPortNum(portNum);
                //添加油卡临时数据库
                CardTempModle cardTemp = new CardTempModle();
                cardTemp.setGunNum(GunInfoDao.getInstance().queryBytPortNum(portNum).getGunNum());
                cardTemp.setPortNum(portNum);
                cardTemp.setPointAmount(cardInfoBean.getPointAmount());
                cardTemp.setCardLevel(cardInfoBean.getCardLevel());
                cardTemp.setCardId(cardInfoBean.getId());
                cardTemp.setCardNum(cardInfoBean.getCardNum());
                cardTemp.setType(cardInfoBean.getType());
                cardTemp.setBalance(cardInfoBean.getBalance());
                cardTemp.setPhone(cardInfoBean.getPhone());
                cardTemp.setName(cardInfoBean.getName());
                cardTemp.setState(cardInfoBean.getState());
                cardTemp.setPwd(cardInfoBean.getPwd());
                cardTemp.setGunId(cardInfoBean.getGunId());
                cardTemp.setCardDiscount(cardInfoBean.getCardDiscount());

                CardTempDao.getInstance().update(cardTemp);
            }
        });
        replaceFragment(portNum, cardInfoFgFragment, mPresenter.getFramLayoutIdBySerialNum(portNum), CardInfoFgFragment.class.getName() + portNum);
    }

    /**
     * 显示加油中
     *
     * @param portNum 串口号
     */
    private void showFueling(String portNum, Receive_MachineState cmd_state, boolean isFueling) {

        Fragment fragment = getSupportFragmentManager().findFragmentByTag(FuelingFgFragment.class.getName() + portNum);
        FuelingFgFragment fuelingFgFragment;
        if (fragment == null) {
            fuelingFgFragment = new FuelingFgFragment();
            fuelingFgFragment.setINextFragment(new INextFragment() {
                @Override
                public void replaceNext(Intent intent, String className) {

                }
            });
            replaceFragment(portNum, fuelingFgFragment, mPresenter.getFramLayoutIdBySerialNum(portNum), FuelingFgFragment.class.getName() + portNum);

        } else {
            if (fragment instanceof FuelingFgFragment) {
                fuelingFgFragment = (FuelingFgFragment) fragment;
                String oilTypeName = GunInfoDao.getInstance().queryBytPortNum(portNum).getTypeShortName();
                fuelingFgFragment.updateUIDatas(oilTypeName, cmd_state);
            } else {
                Log.d(TAG, "showFueling() returned: " + "加油中---的界面异常");
            }
        }
    }

    /**
     * 显示支付选择界面
     *
     * @param portNum
     * @param cmd_end
     * @param isOnlyCash 只能现金支付
     */
    private void showPayChoose(final String portNum, final Receive_EndFueling cmd_end, boolean isOnlyCash) {

        PayChooseFragment payChooseFg = new PayChooseFragment(portNum, cmd_end, isOnlyCash);
        payChooseFg.setINextFragment(new INextFragment() {
            @Override
            public void replaceNext(Intent intent, String className) {
                if (className.equals(PayResFragment.class.getName())) {
                    //现金支付调用接口成功
                    String payType = intent.getStringExtra("payType");
                    if (Common.PAY_MODE_CASH.equals(payType)) {
                        if (Common.IS_EXCETPION_ORDER_USE) {
                            ExceptionOrderDao.getInstance().updateOrderPayState(portNum, Common.ORDER_PAYED, "");
                        } else {
                            TempOrderDao.getInstance().updateOrderPayState(portNum, Common.ORDER_PAYED);
                        }
                        //下发写卡信息
                        mPresenter.port_sendWriteCard_9101(portNum, cmd_end);
                        mPresenter.http_payByCash(portNum, false, "");

                    }
                } else if (className.equals(ErWeiMaFragment.class.getName())) {
                    //跳转二维码界面
                    showErWeiMa(portNum, intent, cmd_end);
                }else if (className.equals(TopFgFragment.class.getName())){
                    //订单异常,只能采用现金支付,然后在现金支付界面点击了返回按钮,就会走到此处
                    String payType = intent.getStringExtra("payType");
                    if (Common.PAY_MODE_CASH.equals(payType)) {
                        if (Common.IS_EXCETPION_ORDER_USE) {
                            ExceptionOrderDao.getInstance().updateOrderPayState(portNum, Common.ORDER_PAYED, "");
                        } else {
                            TempOrderDao.getInstance().updateOrderPayState(portNum, Common.ORDER_PAYED);
                        }
                        //下发写卡信息
                        mPresenter.port_sendWriteCard_9101(portNum, cmd_end);
                        mPresenter.http_payByCash(portNum, false, "");
                    }
                    showTop(portNum,false);
                }
            }
        });
        replaceFragment(portNum, payChooseFg, mPresenter.getFramLayoutIdBySerialNum(portNum), PayChooseFragment.class.getName() + portNum);

    }

    /**
     * 显示支付二维码界面
     *
     * @param portNum
     * @param intent
     * @param cmd_end
     */
    public void showErWeiMa(final String portNum, Intent intent, final Receive_EndFueling cmd_end) {
        ErWeiMaFragment erWeiMaFragment = new ErWeiMaFragment(intent, portNum);
        erWeiMaFragment.setINextFragment(new INextFragment() {
            @Override
            public void replaceNext(Intent intent, String className) {
                if (className.equals(PayChooseFragment.class.getName())) {
                    showPayChoose(portNum, cmd_end, false);
                } else if (className.equals(PayResFragment.class.getName())) {
                    String payType = intent.getStringExtra("payType");
                    String amount = intent.getStringExtra("amount");
                    mPresenter.port_sendWriteCard_9101(portNum, cmd_end);
                    showPayRes(portNum, payType, amount);

                }
            }
        });
        replaceFragment(portNum, erWeiMaFragment, mPresenter.getFramLayoutIdBySerialNum(portNum), ErWeiMaFragment.class.getName() + portNum);
    }

    /**
     * 显示支付成功界面
     *
     * @param portNum
     * @param payType
     */
    private void showPayRes(final String portNum, String payType, String amount) {
        PayResFragment payResFg = new PayResFragment(payType, amount);
        payResFg.setINextFragment(new INextFragment() {
            @Override
            public void replaceNext(Intent intent, String className) {
                if (className.equals(TopFgFragment.class.getName())) {
                    showTop(portNum, false);
                }
            }
        });
        replaceFragment(portNum, payResFg, mPresenter.getFramLayoutIdBySerialNum(portNum), PayResFragment.class.getName() + portNum);
    }

    /**
     * 预约订单查询
     *
     * @param portNum 串口号
     */
    private void showOrderInfoQuery(final String portNum) {
        OrderInfoFgFragment orderInfoFgFragment = new OrderInfoFgFragment(portNum);
        orderInfoFgFragment.setINextFragment(new INextFragment() {
            @Override
            public void replaceNext(Intent intent, String className) {
                if (TopFgFragment.class.getName().equals(className)) {
                    portNumPreOrder.put(portNum, false);//空闲时候,将预约显示为false
                    showTop(portNum, false);
                }
            }
        });
        orderInfoFgFragment.setShowOrderNumListener(new OrderInfoFgFragment.ShowOrderNumListener() {
            @Override
            public void showOrderNum(String orderNum) {
                portNumPreOrderNum.put(portNum, orderNum);
                //更新订单号
                if (Common.IS_EXCETPION_ORDER_USE) {
                    ExceptionOrderDao.getInstance().upadteOrderNum(portNum, orderNum);
                } else {
                    TempOrderDao.getInstance().upadteOrderNum(portNum, orderNum);
                }
            }
        });
        replaceFragment(portNum, orderInfoFgFragment, mPresenter.getFramLayoutIdBySerialNum(portNum), OrderInfoFgFragment.class.getName() + portNum);
    }

    /**
     * 显示错误界面
     *
     * @param portNum
     * @param noticeStr
     * @param className
     */
    @Override
    public void showErrorUI(String portNum, String noticeStr, String className) {
        ErrorFragment errorFragment = new ErrorFragment(noticeStr, className);
        replaceFragment(portNum, errorFragment, mPresenter.getFramLayoutIdBySerialNum(portNum), ErrorFragment.class.getName() + portNum);
    }

    @Override
    public String getPreOrderNumByPortNum(String portNum) {
        return portNumPreOrderNum.get(portNum);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_set:
                if (!checkIsWorking()) {
                    startActivity(new Intent(mActivity, SetActivity.class));
                    finish();
                } else {
                    CustomToast.showToast(mContext, "油机工作中...");
                }
                break;
        }
    }

    /**
     * 检验 油机是否工作中
     *
     * @return
     */
    public boolean checkIsWorking() {
        boolean isWorking = false;
        for (Map.Entry<String, String> entry : stateSerialNumMap.entrySet()) {
            if (Common.OIL_STATE_FREE.equalsIgnoreCase(entry.getValue()) || Common.OIL_STATE_OFFLINE.equalsIgnoreCase(entry.getValue())) {
                isWorking = false;
            } else {
                return true;
            }
        }
        return isWorking;
    }


    /**
     * 联网请求结果:  显示油枪信息
     *
     * @param gunsInfoResBean 油枪
     */
    @Deprecated
    @Override
    public void showTopGunsInfoResult(WsResTopGunsInfoBean gunsInfoResBean) {

    }

    /**
     * 显示油枪个数
     *
     * @param gunsCount
     */
    @Override
    public void showGunsCountUI(int gunsCount) {
        if (gunsCount == 1) {
            frame_left.setVisibility(View.VISIBLE);
            frame_right.setVisibility(View.GONE);
        } else if (gunsCount == 2) {
            frame_left.setVisibility(View.VISIBLE);
            frame_right.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 油卡加油成功创建订单
     *
     * @param portNum
     * @param cmd_end
     */
    @Override
    public void showCreateOrderByOilCard(String portNum, Receive_EndFueling cmd_end, boolean isCreateSuccess, String errorMsg) {
        if (isCreateSuccess) {
            //提交订单到云平台成功
            //如果是员工卡,跳转支付选择接口;如果是用户卡,直接显示支付结果
            // 1用户的加油卡 2员工卡
            if ("1".equals(CardTempDao.getInstance().queryByPortNum(portNum).getType())) {
                //下发写卡信息
                mPresenter.port_sendWriteCard_9101(portNum, cmd_end);
                //用户卡支付
                mPresenter.http_payByUserCard(portNum);
                //油卡支付
                if (Common.IS_EXCETPION_ORDER_USE) {
                    ExceptionOrderDao.getInstance().upadteOrderPayMode(portNum, Common.PAY_MODE_CARD);
                } else {
                    TempOrderDao.getInstance().upadteOrderPayMode(portNum, Common.PAY_MODE_CARD);
                }
            } else {
                // 员工卡支付 跳转 支付选择界面
                showPayChoose(portNum, cmd_end, false);
            }
            // TODO: 2018/4/10 0010 更新订单表 写卡失败 ,如果写卡成功则会 状态由加油结束变为空闲??此时再调用油卡支付接口和更新订单表为支付成功
        } else {
            //经过三次提交订单失败后,跳转支付结果页面,显示网络异常,请选择现金支付
            // TODO: 2018/4/26 0026

            // 用户卡进行提示, 员工卡 走现金支付           1用户的加油卡 2员工卡
            if ("1".equals(CardTempDao.getInstance().queryByPortNum(portNum).getType())) {
                showErrorUI(portNum, errorMsg
                        + "\n本次加油:" + HexUtils.formatDouble(cmd_end.getSheng(), 2) + "升"
                        + "\n油卡需付:" + cmd_end.getRealMoney() + "元"
                        + ",\n异常订单已存储本地!", null);
            } else {
                showPayChoose(portNum, cmd_end, true);
            }

            //下发写卡信息
            mPresenter.port_sendWriteCard_9101(portNum, cmd_end);
        }
    }

    /**
     * 显示预约订单http提交结果
     *
     * @param portNum
     * @param cmd_end
     * @param isCreateSuccess
     * @param errorMsg
     */
    @Override
    public void showPreOrderCreate(String portNum, Receive_EndFueling cmd_end, boolean isCreateSuccess, String errorMsg) {
        // TODO: 2018/5/12 0012 上传失败 (uploadState 是否上传  0 未上传 1已上传)
        if (isCreateSuccess) {
            //订单更新订单
            if (Common.IS_EXCETPION_ORDER_USE) {
                ExceptionOrderDao.getInstance().updateOrderUploadState(portNum, true, "");
            } else {
                TempOrderDao.getInstance().setOrderUploadState(portNum, true);
            }
            mPresenter.port_sendWriteCard_9101(portNum, cmd_end);
            showPayRes(portNum, Common.PAY_MODE_ORDER, cmd_end.getRealMoney() + "");
        } else {
            mPresenter.port_sendWriteCard_9101(portNum, cmd_end);
            //订单更新订单状态
            if (Common.IS_EXCETPION_ORDER_USE) {
                ExceptionOrderDao.getInstance().updateOrderUploadState(portNum, false, errorMsg);
            } else {
                TempOrderDao.getInstance().setOrderUploadState(portNum, false);
            }
            showPayRes(portNum, Common.PAY_MODE_ORDER, cmd_end.getRealMoney() + "");
        }

    }

    /**
     * 用户油卡支付
     *
     * @param portNum
     * @param bean
     */
    @Override
    public void showPayUserCardSuccess(String portNum, WsResPayByCard bean) {
        showPayRes(portNum, Common.PAY_MODE_CARD, bean.getAmount());
    }

    /**
     * 现金支付
     *
     * @param resBean
     */
    @Override
    public void showPayByCashSuccess(String portNum, PayByCashResBean resBean) {
        showPayRes(portNum, Common.PAY_MODE_CASH, resBean.getAmount());
    }

    @Override
    public void showPayByCashFailed(String portNum, String errorMsg) {
        showErrorUI(portNum, "现金支付失败!\n订单已暂存本地!", null);
    }

    @Override
    public String getCurrentState(String portNum) {
        return stateSerialNumMap.get(portNum);
    }

    /**
     * 显示广告
     */
    @Override
    public void showTopAd() {

    }

    /**
     * 空闲(0X00)
     *
     * @param portNum 串口号
     */
    @Override
    public void machineStateFree_00(final String portNum, Receive_MachineState cmd_state) {
        if (TestCommon.isShowMainToast) {
            CustomToast.showToast(mContext, mPresenter.getFramLayoutIdBySerialNum(portNum) + "侧油枪空闲" + portNum);
        }
        String lastState = stateSerialNumMap.get(portNum) == null ? Common.OIL_STATE_OFFLINE : stateSerialNumMap.get(portNum);//油机某端口上次的状态
        stateSerialNumMap.put(portNum, Common.OIL_STATE_FREE);

        switch (lastState) {
            case Common.OIL_STATE_FREE://空闲
//                //如果是异常界面,则跳转空闲 ,
                if ((ErrorFragment.class.getName() + portNum).equals(currentFragmentTag.get(portNum))) {
                    showTop(portNum, false);
                    return;
                }

                WsResTopGunsInfoBean.OilGunOutputBean oilGunBeanByPortNum = mPresenter.getOilGunBeanByPortNum(portNum);
                //空闲时,查看油机的价格和云端获取到的价格是否一致,如果不一致,就进行修改价格;(一天最多修改两次价格)
                //查看云端的[油品名称]及[油站名称]与 油机本地的[油品名称]和 [油站名称]是否一致,不一致则进行修改
                double localTypePrice = ArithUtil.round(ArithUtil.mul(HexUtils.hex2Int(cmd_state.getUnit_priceStr()), 0.01), 2);//油品的单价
                double yunTypePriceDouble = ArithUtil.round(Double.parseDouble(oilGunBeanByPortNum.getCuPrice()), 2);//云端价格

                String localTypeName = GunInfoDao.getInstance().queryBytPortNum(portNum).getTypeName();
                String yunTypeName = oilGunBeanByPortNum.getTypeName();

                String localStationName = ClientInfoDao.getInstance().getModleByDeviceNum().getStationName();
                String yunStationName = oilGunBeanByPortNum.getSellerName();

                String machineGunNum = cmd_state.getGunNumHead_1();//本地油机油枪号和云端油枪号对比
                String yunGunNum = oilGunBeanByPortNum.getGunNum();

                if ((!machineGunNum.equals(yunGunNum) && !(Integer.parseInt(cmd_state.getGunNumHead_1(), 16) + "").equals(yunGunNum))
                        || localTypePrice != yunTypePriceDouble || !localTypeName.equals(yunTypeName)
                        || !localStationName.equals(yunStationName)) {
                    Log.d(TAG, "machineStateFree_00() returned: " + "发生了变价调整");
                    mPresenter.port_sendSetMachine_1104(portNum, cmd_state);
                    mPresenter.port_sendSetCardMachine_910A(portNum, cmd_state);
                    showTop(portNum, true);
                } else {
                    Log.d(TAG, "machineStateFree_00() returned: " + "不再变价");
                }
                break;
            case Common.OIL_STATE_LOCK://锁机
            case Common.OIL_STATE_FUELING://加油中..
            case Common.OIL_STATE_OFFLINE://离线
            case Common.OIL_STATE_CARD_IN://卡已插入,授权有卡
                mPresenter.httpUpdateState(portNum);
                showTop(portNum, false);
                break;
            case Common.OIL_STAT_PREPARE://加油前准备
                mPresenter.httpUpdateState(portNum);
                showTop(portNum, false);
                break;
            case Common.OIL_STATE_BILLING://加油结束
                // TODO: 2018/4/4 0004 订单提交失败 会出现此种情况
                mPresenter.httpUpdateState(portNum);
//                showTop(portNum, false);//开启此处,加油结束后,的加油结果就无法长时间显示了
                break;
        }

    }

    /**
     * 加油中(0X0F)
     *
     * @param portNum   串口号
     * @param cmd_state
     */
    @Override
    public void machineStateFueling_0F(final String portNum, Receive_MachineState cmd_state) {
        String lastState = stateSerialNumMap.get(portNum) == null ? Common.OIL_STATE_OFFLINE : stateSerialNumMap.get(portNum);//油机某端口上次的状态
        stateSerialNumMap.put(portNum, Common.OIL_STATE_FUELING);

        switch (lastState) {
            case Common.OIL_STATE_FUELING://加油中
                Log.d(TAG, "machineStateFueling_0F() returned: " + "加油中-----");
                showFueling(portNum, cmd_state, true);
                // 加油过程中不断刷新 保存加油中的加油金额,加油量
                if (Common.IS_EXCETPION_ORDER_USE) {
                    ExceptionOrderDao.getInstance().updateFuelingData_2(portNum, cmd_state);
                } else {
                    TempOrderDao.getInstance().updateFuelingData_2(portNum, cmd_state);
                }
                break;
            case Common.OIL_STATE_OFFLINE://离线
            case Common.OIL_STATE_CARD_IN://授权有卡 // TODO: 2018/4/24 0024 如果操作(下发卡信息后,直接加油(很快),就会出现此情况) 
            case Common.OIL_STAT_PREPARE://加油前准备
                //加油中
                Log.d(TAG, "machineStateFueling_0F() returned: " + "加油开始-----");
                showFueling(portNum, cmd_state, false);
                mPresenter.httpUpdateState(portNum);

                if (portNumPreOrder.get(portNum) == null ? false : portNumPreOrder.get(portNum)) {//预约
                    //创建加油订单表 预约
                    if (Common.IS_EXCETPION_ORDER_USE) {
                        ExceptionOrderDao.getInstance().createOrder_1(portNum, portNumPreOrderNum.get(portNum), Common.ORDER_TYPE_ORDERED);
                    } else {
                        TempOrderDao.getInstance().createNewOrder_1(portNum, portNumPreOrderNum.get(portNum), Common.ORDER_TYPE_ORDERED);
                    }
                } else {
                    //创建加油订单表 未预约
                    if (Common.IS_EXCETPION_ORDER_USE) {
                        ExceptionOrderDao.getInstance().createOrder_1(portNum, portNumPreOrderNum.get(portNum), Common.ORDER_TYPE_NOORDERED);
                    } else {
                        TempOrderDao.getInstance().createNewOrder_1(portNum, portNumPreOrderNum.get(portNum), Common.ORDER_TYPE_NOORDERED);
                    }
                }
                break;
        }
    }

    /**
     * 锁机(0X0A)
     *
     * @param portNum 串口号
     */
    @Override
    public void machineStateLock_0A(final String portNum) {
        if (TestCommon.isShowMainToast) {
            CustomToast.showToast(mContext, mPresenter.getFramLayoutIdBySerialNum(portNum) + "侧油枪锁机" + portNum);
        }
        //锁机
        String lastState = stateSerialNumMap.get(portNum) == null ? Common.OIL_STATE_OFFLINE : stateSerialNumMap.get(portNum);//油机某端口上次的状态
        stateSerialNumMap.put(portNum, Common.OIL_STATE_LOCK);
        switch (lastState) {
            case Common.OIL_STATE_LOCK:
                break;
            default:
                showErrorUI(portNum, "锁机中", null);
                mPresenter.httpUpdateState(portNum);
                break;
        }
    }

    /**
     * 离线  (-1)
     *
     * @param portNum 串口号
     */
    @Override
    public void machineStateOffline(final String portNum) {
        //离线
        if (TestCommon.isShowMainToast) {
            CustomToast.showToast(mContext, mPresenter.getFramLayoutIdBySerialNum(portNum) + "侧串口离线" + portNum);
        }

        String lastState = stateSerialNumMap.get(portNum) == null ? Common.OIL_STATE_OFFLINE : stateSerialNumMap.get(portNum);//油机某端口上次的状态
        stateSerialNumMap.put(portNum, Common.OIL_STATE_OFFLINE);
        switch (lastState) {
            case Common.OIL_STATE_OFFLINE:
                break;
            default:
                //预约加油  全部金额加完之后,就读取不到串口数据了,此时不设置为离线,仍显示加油结束
                if (!stateSerialNumMap.get(portNum).equalsIgnoreCase(Common.OIL_STATE_GUN_DOWN)) {
                    showErrorUI(portNum, "油机异常\n串口连接失败", null);
                    mPresenter.httpUpdateState(portNum);
                }
                break;
        }
    }

    /**
     * 授权有卡(0X02)
     *
     * @param portNum 串口号
     */
    @Override
    public void machineStateCard_02(final String portNum) {
        String lastState = stateSerialNumMap.get(portNum) == null ? Common.OIL_STATE_OFFLINE : stateSerialNumMap.get(portNum);//油机某端口上次的状态
        //授权有卡
        if (TestCommon.isShowMainToast) {
            CustomToast.showToast(mContext, mPresenter.getFramLayoutIdBySerialNum(portNum) + "侧授权油卡" + portNum);
        }
        stateSerialNumMap.put(portNum, Common.OIL_STATE_CARD_IN);

        switch (lastState) {
            case Common.OIL_STATE_CARD_IN:

                break;
            case Common.OIL_STATE_FUELING:

                break;
            case Common.OIL_STATE_OFFLINE://卡已经插入了,但是油机串口断开,然后又恢复的情况
                CardTempDao.getInstance().queryByPortNum(portNum).getCardNum();
                break;
            default:
                mPresenter.httpUpdateState(portNum);
                break;
        }
    }

    /**
     * 加油前准备(0X03)
     *
     * @param portNum     串口号
     * @param cmd_prepare 油机返回命令
     */
    @Override
    public void machinePrepareFueling(final String portNum, Receive_PrepareFueling cmd_prepare) {
        //加油前准备,开始下发卡信息；
        String lastState = stateSerialNumMap.get(portNum) == null ? Common.OIL_STATE_OFFLINE : stateSerialNumMap.get(portNum);//油机某端口上次的状态
        if (TestCommon.isShowMainToast) {
            CustomToast.showToast(mContext, mPresenter.getFramLayoutIdBySerialNum(portNum) + "侧右加油前准备，准备下发卡信息" + portNum);
        }
        stateSerialNumMap.put(portNum, Common.OIL_STAT_PREPARE);
        Log.d(TAG, "machinePrepareFueling() returned: " + cmd_prepare);

//        Fragment fragment = getSupportFragmentManager().findFragmentByTag(CardInfoFgFragment.class.getName());
//        if (fragment != null) {
//            Log.d(TAG, "---------: " + fragment.getClass().getName());
//        } else {
//            mPresenter.httpUpdateState(portNum);
//            showCardInfo(portNum, cmd_prepare);
//        }

        switch (lastState) {
            case Common.OIL_STAT_PREPARE:

                break;
            case Common.OIL_STATE_OFFLINE://离线
            case Common.OIL_STATE_FREE:
                //显示油卡界面,在油卡界面获取卡信息,然后发送 下发卡信息命令
                mPresenter.httpUpdateState(portNum);
                showCardInfo(portNum, cmd_prepare);
                break;
            default:

                break;
        }
    }

    /**
     * 加油结束(0XF0)
     *
     * @param portNum 串口号
     */
    @Override
    public void machineEndFueling(final String portNum, Receive_EndFueling cmd_end) {
        String lastState = stateSerialNumMap.get(portNum) == null ? Common.OIL_STATE_OFFLINE : stateSerialNumMap.get(portNum);//油机某端口上次的状态
        //结束加油(状态改为 结算中)
        if (TestCommon.isShowMainToast) {
            CustomToast.showToast(mContext, mPresenter.getFramLayoutIdBySerialNum(portNum) + "结束加油" + portNum);
        }
        stateSerialNumMap.put(portNum, Common.OIL_STATE_BILLING);
        // TODO: 2018/3/29 0029 加油结束 更新状态
        //还有一种情况,加油中断开了,然后,一开机就是加油结束的命令
        switch (lastState) {
            case Common.OIL_STATE_BILLING://加油结束 (如果写卡失败,会一直发加油结束命令,
                break;
            case Common.OIL_STATE_OFFLINE://离线
            case Common.OIL_STATE_FUELING://加油中
            case Common.OIL_STATE_CARD_IN://授权油卡
                // TODO: 2018/4/9 0009 加油结束前,可能(大概率)会收到一帧或两针授权有卡命令
                // TODO: 2018/5/12 0012 写卡操作要与联网操作并行,以保证即使联网操作失败,也能继续油机操作 ,但是要标记创建订单的状态
                //加油结束后,立即更新加油的临时订单数据
                if (Common.IS_EXCETPION_ORDER_USE) {
                    ExceptionOrderDao.getInstance().updateFueledData_3(portNum, cmd_end);
                } else {
                    TempOrderDao.getInstance().updateFueledData_3(portNum, cmd_end);
                }
                //保存流水号,以备修改价格使用
                SpUtils.getInstance(mContext).savePingZhengHao(cmd_end.getErialNum_2());
                mPresenter.createOrder(portNum, cmd_end, 0);
                portNumPreOrder.put(portNum, false);
                break;
            default:
                break;
        }
    }

    @Override
    public void preOrderRes(String porNum, String datas) {
        //发送定量的返回
        if ("01".equals(datas)) {//成功
            portNumPreOrder.put(porNum, true);
        } else {
            portNumPreOrder.put(porNum, false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void initCommunication() {
        stateSerialNumMap = new HashMap<>();
        fuelFgSerialNumMap = new HashMap<>();
        topFgSerialNumMap = new HashMap<>();
        portNumPreOrder = new HashMap<>();
        portNumPreOrderNum = new HashMap<>();
        currentFragmentTag = new HashMap<>();
        fm = getSupportFragmentManager();

        mPresenter = new MainFuelPresenter(mContext, this);

        //获取首页油枪信息
        mPresenter.http_GetLoopGunInfo();


        //打开websocket
        mPresenter.ws_openWebscoket();
    }

    @Override
    public void onPause() {
        super.onPause();
//        mPresenter.http_stopGetLoopGunInfo();
//        SerialPortToolManager.getInstance().closeAll();
    }

    //-------------轮播图---------------------------------------------------------------------------------------------------
    private NoPreloadViewPager mVp;
    //    private int[] images;// 存放所有要显示的图片资源id
    private List<View> imgList = new ArrayList<View>();
    // 存放要显示在ViewPager对象中的所有Imageview对象
    private int prevPosition = 0;
    private Handler handler = new Handler() {

        @SuppressLint("HandlerLeak")
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case ERROR_HTTP_CYCLE:
                    //异常http提交循环
                    for (Request request : MyApp.errorRequests) {
                        Log.e(TAG, "异常http提交: " + "提交异常http");
                        OkhttpUtils.getInstance().postErrorRequest(request);
                    }
                    //60秒一循环
                    handler.sendEmptyMessageDelayed(ERROR_HTTP_CYCLE, 6 * 1000);
                    break;
                case UPTATE_VIEWPAGER:
                    if (msg.arg1 != 0) {
                        mVp.setCurrentItem(msg.arg1);
                    } else {
                        //false 当从末页调到首页时，不显示翻页动画效果，
                        mVp.setCurrentItem(msg.arg1, false);
                    }
                    break;
                default:
                    break;
            }
        }
    };


    /**
     * 展示广告信息数据 (此处网络图片不取,只从下载地址取广告轮播)
     *
     * @param resBean
     */
    @Override
    public void showAdListUI(ADListResBean resBean) {
        handler.removeCallbacks(lubotu);
        if (adList2 == null) {
            adList2 = resBean.getAdList();
//            autoBanner(adList2, false);
        } else {
            adList2.clear();
            adList2.addAll(resBean.getAdList());
//            autoBanner(adList2, true);
        }
    }

    /**
     * @param httpAdBeans 网络请求回来的视频集合  x需要显示的视频
     * @param adModles    本地视频集合
     *                    进行对比,如果本地视频包含 需要显示的视频,则显示此本地视频,如果没有,不显示
     */
    @Override
    public void showAdListUI_Local(List<ADListResBean.AdListBean> httpAdBeans, List<AdModle> adModles) {
        //对比 网络数据和本地数据,如果本地有多余的数据,就删除掉
        List<AdModle> tempModles = new ArrayList<>();
        for (int i = 0; i < adModles.size(); i++) {//数据库中的同时也是本地的
            if (httpAdBeans != null) {
                for (ADListResBean.AdListBean httpAd : httpAdBeans) {//网络的数据
                    if (httpAd.getImgPath().equals(adModles.get(i).getHttpImgPath())) {
                        tempModles.add(adModles.get(i));
//                        Log.d(TAG, "本地视频存在===: " + httpAd.getImgPath());
                    } else {
//                        Log.d(TAG, "本地视频没有: " + httpAd.getImgPath() + "本地存储没有:" + adModles.get(i).getHttpImgPath());
                    }
                }
            } else {
                tempModles.add(adModles.get(i));
            }
        }
        AdDao.getInstance().deleteAll();
        AdDao.getInstance().saveAdList(tempModles);

        if (adModleList == null) {
            adModleList = tempModles;
            autoBanner(adModleList, false);
        } else {
            if (tempModles != null && tempModles.size() != 0) {
                adModleList.clear();
                adModleList.addAll(tempModles);
//                handler.removeCallbacks(lubotu);
//                autoBanner(adModleList, true);
            } else {
                Log.d(TAG, "showAdListUI_Local() returned: tempModles == null");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SerialPortToolManager.getInstance().closeAll();
        mPresenter.http_stopGetLoopGunInfo();
        mPresenter.http_stopGetAdListInfo();
        Log.d(TAG, "====----====: " + "销毁activity");
        handler.removeCallbacks(lubotu);
    }

    private int autoCurrIndex = 0;//设置当前 第几个图片 被选中

    private static final int UPTATE_VIEWPAGER = 3;

    public Runnable lubotu = new Runnable() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = UPTATE_VIEWPAGER;
            if (autoCurrIndex == adModleList.size() - 1) {
                autoCurrIndex = -1;
            }
            message.arg1 = autoCurrIndex + 1;
            handler.sendMessage(message);
        }
    };

    private void autoBanner(final List<AdModle> list, boolean refresh) {
        if (list == null || list.size() == 0){
            return;
        }
        Log.d(TAG, "延迟kaishi "  );
        if (refresh) {
            autoCurrIndex = 0;
            mVp.setCurrentItem(autoCurrIndex);
            adPagerAdapter2.notifyDataSetChanged();
        } else {
            adPagerAdapter2 = new AdPagerAdapter(mActivity, list);
            adPagerAdapter2.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.d(TAG, "onError() returned: " + "视频播放出错");
                    mVp.setCurrentItem(autoCurrIndex+1);
                    return true;
                }
            });
            mVp.setAdapter(adPagerAdapter2);

            mVp.setOnPageChangeListener(new NoPreloadViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    Log.d(TAG, "onPageScrolled()滑动: " + position);
                }

                @Override
                public void onPageSelected(int position) {
                    handler.removeCallbacks(lubotu);
                    if (autoCurrIndex == 0){
                        Log.d(TAG, "onPageSelected() returned: " + "延迟到第一页了" );
                        adPagerAdapter2.notifyDataSetChanged();
                    }
                    autoCurrIndex = position;//动态设定轮播图每一页的停留时间
                    handler.postDelayed(lubotu, (list.get(position).getTimeLong() == 0 ? 5 : list.get(position).getTimeLong()) * 1000);
                    Log.d(TAG, "onPageSelected() returned: " + "延迟" + (list.get(position).getTimeLong() == 0
                            ? 5 : list.get(position).getTimeLong()) * 1000 + "s,跳转到第" + (autoCurrIndex+2) + "页");

                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }

        handler.postDelayed(lubotu, (list.get(autoCurrIndex).getTimeLong() == 0
                ? 5 : list.get(autoCurrIndex).getTimeLong()) * 1000);
        Log.d(TAG, "onPageSelected() returned: " + "第延迟" + (list.get(autoCurrIndex).getTimeLong() == 0
                ? 5 : list.get(autoCurrIndex).getTimeLong()) * 1000 + "s,跳转到第" + (autoCurrIndex+2) + "页");
    }
}
